/**
 * Gitee API 封装类
 * 处理与Gitee仓库的所有交互
 */
class GiteeAPI {
    constructor() {
        this.baseUrl = 'https://gitee.com/api/v5';
        this.token = '';
        this.owner = '';
        this.repo = '';
        
        // 数据文件路径配置
        this.dataPaths = {
            demands: 'data/demands.json',
            workflows: 'data/workflows.json',
            users: 'data/users.json',
            config: 'data/config.json',
            demandTypes: 'data/demand-types.json',
            urgencyLevels: 'data/urgency-levels.json'
        };
    }
    
    /**
     * 初始化API
     */
    async initialize() {
        // 从本地存储加载配置
        this.token = localStorage.getItem('gitee_token') || '';
        this.owner = localStorage.getItem('gitee_owner') || 'Rovinty';
        this.repo = localStorage.getItem('gitee_repo') || 'task-track';
        
        return { success: true };
    }
    
    /**
     * 设置认证信息
     */
    setAuth(token, owner, repo) {
        this.token = token;
        this.owner = owner;
        this.repo = repo;
        
        // 保存到本地存储
        localStorage.setItem('gitee_token', token);
        localStorage.setItem('gitee_owner', owner);
        localStorage.setItem('gitee_repo', repo);
    }
    
    /**
     * 获取认证信息
     */
    getAuth() {
        return {
            token: this.token,
            owner: this.owner,
            repo: this.repo
        };
    }
    
    /**
     * 检查是否已配置认证
     */
    isConfigured() {
        return !!(this.token && this.owner && this.repo);
    }
    
    /**
     * 测试连接
     */
    async testConnection() {
        if (!this.isConfigured()) {
            return {
                success: false,
                message: '请先配置Gitee访问令牌'
            };
        }
        
        try {
            const response = await fetch(`${this.baseUrl}/repos/${this.owner}/${this.repo}?access_token=${this.token}`);
            
            if (response.ok) {
                const repoInfo = await response.json();
                return {
                    success: true,
                    message: '连接成功',
                    repoInfo: {
                        name: repoInfo.name,
                        description: repoInfo.description,
                        private: repoInfo.private,
                        updated_at: repoInfo.updated_at
                    }
                };
            } else {
                const error = await response.json();
                return {
                    success: false,
                    message: error.message || '连接失败'
                };
            }
        } catch (error) {
            return {
                success: false,
                message: '网络错误: ' + error.message
            };
        }
    }
    
    /**
     * 获取文件内容
     */
    async getFile(path) {
        // 如果没有配置Gitee，抛出错误
        if (!this.isConfigured()) {
            throw new Error('Gitee未配置，请先配置访问令牌');
        }
        
        try {
            const response = await fetch(
                `${this.baseUrl}/repos/${this.owner}/${this.repo}/contents/${path}?access_token=${this.token}`
            );
            
            if (response.ok) {
                const data = await response.json();
                const content = atob(data.content.replace(/\n/g, ''));
                return {
                    success: true,
                    data: JSON.parse(content),
                    sha: data.sha
                };
            } else if (response.status === 404) {
                throw new Error('文件不存在');
            } else if (response.status === 401) {
                throw new Error('访问令牌无效或已过期');
            } else {
                const error = await response.json();
                throw new Error(error.message || '获取文件失败');
            }
        } catch (error) {
            throw error;
        }
    }
    
    /**
     * 创建或更新文件
     */
    async saveFile(path, content, message = '更新数据') {
        if (!this.isConfigured()) {
            throw new Error('Gitee未配置，请先配置访问令牌');
        }
        
        try {
            // 先尝试获取文件信息（用于更新）
            let sha = null;
            try {
                const existingFile = await this.getFile(path);
                if (existingFile.success) {
                    sha = existingFile.sha;
                }
            } catch (error) {
                // 文件不存在，继续创建
            }
            
            const requestBody = {
                access_token: this.token,
                message: `${message} - ${new Date().toLocaleString()}`,
                content: btoa(JSON.stringify(content, null, 2))
            };
            
            // 如果文件存在，需要提供sha值
            if (sha) {
                requestBody.sha = sha;
            }
            
            const response = await fetch(
                `${this.baseUrl}/repos/${this.owner}/${this.repo}/contents/${path}`,
                {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestBody)
                }
            );
            
            if (response.ok) {
                const result = await response.json();
                return {
                    success: true,
                    message: '保存成功',
                    sha: result.content.sha
                };
            } else {
                const error = await response.json();
                throw new Error(error.message || '保存失败');
            }
        } catch (error) {
            throw error;
        }
    }
    
    /**
     * 删除文件
     */
    async deleteFile(path, message = '删除文件') {
        if (!this.isConfigured()) {
            throw new Error('Gitee未配置，请先配置访问令牌');
        }
        
        try {
            // 先获取文件信息
            const existingFile = await this.getFile(path);
            
            if (!existingFile.success) {
                throw new Error('文件不存在');
            }
            
            const response = await fetch(
                `${this.baseUrl}/repos/${this.owner}/${this.repo}/contents/${path}`,
                {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        access_token: this.token,
                        message: `${message} - ${new Date().toLocaleString()}`,
                        sha: existingFile.sha
                    })
                }
            );
            
            if (response.ok) {
                return {
                    success: true,
                    message: '删除成功'
                };
            } else {
                const error = await response.json();
                throw new Error(error.message || '删除失败');
            }
        } catch (error) {
            throw error;
        }
    }
    
    /**
     * 获取默认流程配置
     */
    getDefaultWorkflows() {
        return {
            "new_product": {
                "id": "new_product",
                "name": "新品上架",
                "description": "新产品从需求提出到最终上架的完整流程",
                "demandType": "new_product",
                "nodes": [
                    {
                        "id": "submit",
                        "name": "需求提出",
                        "description": "运营人员提出新品上架需求",
                        "defaultAssignee": null,
                        "requiredFields": ["title", "description", "deadline"],
                        "allowedActions": ["confirm", "reject"],
                        "order": 1
                    },
                    {
                        "id": "product_review",
                        "name": "产品评估",
                        "description": "产品团队评估新品可行性",
                        "defaultAssignee": "product_manager",
                        "requiredFields": ["feasibility_report"],
                        "allowedActions": ["confirm", "reject", "request_info"],
                        "order": 2
                    },
                    {
                        "id": "planning",
                        "name": "计划制定",
                        "description": "制定详细的上架计划和时间安排",
                        "defaultAssignee": "planning_specialist",
                        "requiredFields": ["schedule", "resource_allocation"],
                        "allowedActions": ["confirm", "request_adjustment"],
                        "order": 3
                    },
                    {
                        "id": "execution",
                        "name": "执行跟进",
                        "description": "执行上架计划并跟进进度",
                        "defaultAssignee": "execution_manager",
                        "requiredFields": ["progress_report"],
                        "allowedActions": ["confirm", "report_issue"],
                        "order": 4
                    }
                ]
            },
            "promotion": {
                "id": "promotion",
                "name": "促销活动",
                "description": "促销活动策划和执行流程",
                "demandType": "promotion",
                "nodes": [
                    {
                        "id": "submit",
                        "name": "活动提出",
                        "description": "提出促销活动需求",
                        "defaultAssignee": null,
                        "order": 1
                    },
                    {
                        "id": "review",
                        "name": "活动审核",
                        "description": "审核活动方案",
                        "defaultAssignee": "marketing_manager",
                        "order": 2
                    },
                    {
                        "id": "execution",
                        "name": "活动执行",
                        "description": "执行促销活动",
                        "defaultAssignee": "execution_team",
                        "order": 3
                    }
                ]
            }
        };
    }
    
    /**
     * 获取默认用户配置
     */
    getDefaultUsers() {
        return [
            {
                "id": "admin",
                "username": "admin",
                "password": "zxc123456",
                "name": "系统管理员",
                "email": "admin@company.com",
                "roles": ["管理员"],
                "permissions": {
                    "createDemand": true,
                    "editDemand": true,
                    "deleteDemand": true,
                    "viewAllDemands": true,
                    "configureWorkflow": true,
                    "markComplete": true,
                    "addSignNode": true,
                    "manageUsers": true,
                    "systemSettings": true
                },
                "createdAt": "2023-12-01T00:00:00.000Z",
                "lastLogin": null,
                "isActive": true
            }
        ];
    }
    
    /**
     * 获取默认系统配置
     */
    getDefaultConfig() {
        return {
            "version": "2.0.0",
            "lastUpdated": new Date().toISOString(),
            "urgencyCalculation": {
                "urgent": { 
                    "days": 3, 
                    "color": "#dc3545", 
                    "label": "紧急"
                },
                "important": { 
                    "days": 7, 
                    "color": "#ffc107", 
                    "label": "重要"
                },
                "normal": { 
                    "days": 15, 
                    "color": "#28a745", 
                    "label": "正常"
                },
                "low": { 
                    "days": 999, 
                    "color": "#6c757d", 
                    "label": "低优先级"
                }
            }
        };
    }
    
    /**
     * 获取默认需求类型
     */
    getDefaultDemandTypes() {
        return {
            "new_product": {
                "name": "新品上架",
                "color": "#007bff",
                "icon": "🛍️",
                "enabled": true,
                "workflowTemplate": "new_product"
            },
            "promotion": {
                "name": "促销活动",
                "color": "#28a745",
                "icon": "🎉",
                "enabled": true,
                "workflowTemplate": "promotion"
            },
            "inventory": {
                "name": "库存补充",
                "color": "#ffc107",
                "icon": "📦",
                "enabled": true,
                "workflowTemplate": "inventory"
            },
            "price_adjust": {
                "name": "价格调整",
                "color": "#dc3545",
                "icon": "💰",
                "enabled": true,
                "workflowTemplate": "price_adjust"
            }
        };
    }
    
    /**
     * 获取默认紧急度配置
     */
    getDefaultUrgencyLevels() {
        return [
            { "id": 1, "name": "低", "color": "#6c757d", "priority": 1, "days": 999 },
            { "id": 2, "name": "正常", "color": "#28a745", "priority": 2, "days": 15 },
            { "id": 3, "name": "重要", "color": "#ffc107", "priority": 3, "days": 7 },
            { "id": 4, "name": "紧急", "color": "#dc3545", "priority": 4, "days": 3 }
        ];
    }
    
    /**
     * 初始化仓库数据结构
     */
    async initializeRepository() {
        if (!this.isConfigured()) {
            throw new Error('Gitee未配置，请先配置访问令牌');
        }
        
        try {
            const results = await Promise.all([
                this.saveFile(this.dataPaths.demands, [], '初始化需求数据'),
                this.saveFile(this.dataPaths.workflows, this.getDefaultWorkflows(), '初始化流程配置'),
                this.saveFile(this.dataPaths.users, this.getDefaultUsers(), '初始化用户数据'),
                this.saveFile(this.dataPaths.config, this.getDefaultConfig(), '初始化系统配置'),
                this.saveFile(this.dataPaths.demandTypes, this.getDefaultDemandTypes(), '初始化需求类型'),
                this.saveFile(this.dataPaths.urgencyLevels, this.getDefaultUrgencyLevels(), '初始化紧急度配置')
            ]);
            
            const allSuccess = results.every(result => result.success);
            
            return {
                success: allSuccess,
                message: allSuccess ? '仓库初始化成功' : '部分文件初始化失败',
                results
            };
        } catch (error) {
            throw error;
        }
    }
}

// 创建全局实例
window.giteeAPI = new GiteeAPI();